/**
 * 
 */
package serverlogic;

import java.sql.ResultSet;
import java.sql.SQLException;

import net.com.sunkey.protobuf.CheckUserRequest.CheckUserRequestData;
import net.com.sunkey.messagehandler.CheckUserResponseHandler;
import net.com.sunkey.protobuf.Protocol;
import net.com.sunkey.serverlogic.Module;
import net.com.sunkey.serverlogic.Server;

/**
 * @author Administrator
 *
 */
public class ModuleCheckUser extends Module {

	/**
	 * 
	 */
	public ModuleCheckUser() {

	}

	/* (non-Javadoc)
	 * @see net.com.sunkey.serverlogic.Module#invoke(java.lang.Object, java.lang.Object)
	 */
	@Override
	public int invoke(Object data, Object channel) throws Exception {
		System.out.println("["+channel.hashCode()+"]["+Protocol.MessageHandler.CheckUserRequest_VALUE+"]CheckUserRequest");		
		CheckUserRequestData userData=(CheckUserRequestData)data;
		boolean isUsed=findUser(userData.getName());
		return CheckUserResponseHandler.invoke(isUsed,channel);
	}

	/* (non-Javadoc)
	 * @see net.com.sunkey.serverlogic.Module#register()
	 */
	@Override
	public int register() {
		return Protocol.MessageHandler.CheckUserRequest_VALUE;
	}
	
	private boolean findUser(String name) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT id FROM user WHERE name='")
				.append(name).append("'");
		ResultSet rs = Server.getConnection().createStatement().executeQuery(sql.toString());	
		return rs.next();
	}
}
